//
//  FirstViewController.m
//  SleepDetective
//
//  Created by Fei Hu on 12/12/10.
//  Copyright 2010 Southern Methodist University. All rights reserved.
//

#import "TestViewController.h"


@implementation TestViewController
@synthesize progressBar;
@synthesize warningLabel;
@synthesize startBtn;
@synthesize imgStart,imgStop;

/* * * * * * * * * * * * * * * * * * * * *
 *
 *      START PROGRAMMING: FEI HU
 *
 * * * * * * * * * * * * * * * * * * * * */
BOOL isStart; 

// meter noise level
- (void)noiseLevelTest {	

	NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
	
	NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
							  [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
							  [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
							  [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
							  nil];
	
	NSError *error;
	
	recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
	
	if (recorder) {
		[recorder prepareToRecord];
		recorder.meteringEnabled = YES;
		[recorder record];
		levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.01 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
	} else
		NSLog([error description]);		
}

// call back function
- (void)levelTimerCallback:(NSTimer *)timer {
	[recorder updateMeters];
	
	const double ALPHA = 0.05;
	double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0])); //0.0 to 1.0
	double avgPowerForChannel =  pow(10, (0.05 * [recorder averagePowerForChannel:0])); //0.0 to 1.0
	lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;	
	
	// 0dB~-160dB
	//	double ppfc = [recorder peakPowerForChannel:0];
	double peakDecibels = log10f(peakPowerForChannel) * 20; // -inf to 0
	double avgDecibels = log10f(avgPowerForChannel)* 20;
	//decibels = 10 * log10 (lowPassResults);

	self.progressBar.progress = ABS(avgPowerForChannel)*10;	
	
	if (avgPowerForChannel > 0.03 ){
			NSLog(@"Greater than 30dB, TOO Loud");
		warningLabel.text = @"NOISE WARNING!";
		
	} else {
		warningLabel.text = @"";
	}
		
//	NSLog(@"Linear=%f & decibels=%f",avgPowerForChannel, avgDecibels);
	//	NSLog(@"Average input: %f Peak input: %f Low pass results: %f", 
	//		  [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0], lowPassResults);	
}

// Button Action
-(IBAction) startNoiseTesting:(id) sender {
	NSLog(@"--- INFO - TEST NOISE BUTTON -> Start Button Clicked ---");
	imgStart = [UIImage imageNamed:@"start_btn.png"];
	imgStop = [UIImage imageNamed:@"stop_btn.png"];

	isStart = !isStart;	
	if (isStart) {
		[self noiseLevelTest];
		[startBtn setImage:imgStop forState:UIControlStateNormal];
	} else {
		[recorder stop];
		[startBtn setImage:imgStart forState:UIControlStateNormal];
	}

}	
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	NSLog(@"--- INFO - TEST VIEW -> viewDidLoad  ---");	
	isStart = NO;
//	[startBtn setTitle:@"Let's Start!" forState:UIControlStateNormal];
	
//	NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
//	
//	NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
//							  [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
//							  [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
//							  [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
//							  [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
//							  nil];
//	
//	NSError *error;
//	
//	recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
	
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[imgStart release];
	[imgStop release];
	[levelTimer release];
	[recorder release];	
    [super dealloc];
}

@end
